import React, { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  Breadcrumb,
  Card,
  Form,
  Input,
  Space,
  Button,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import Channel from '@/components/Channel/index'
import { PlusOutlined } from '@ant-design/icons'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import {
  addAritcle,
  editArticle,
  getArticleInfo,
} from '@/store/actions/article'
import { useParams, useHistory } from 'react-router-dom'
export default function Publish() {
  const history = useHistory()
  const dispatch = useDispatch()
  //  0.处理富文本插件
  //  1.接收上传文件列表
  const [fileList, setFilelist] = useState([
    // {
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
  ])

  // 3.处理点击 单选按钮的类型 显示图片
  const fileRef = useRef(fileList)
  // 4.上传图片的事件
  const onChange = ({ fileList }) => {
    setFilelist(fileList)
    fileRef.current = fileList

    // 6.校验type
    formRef.current.validateFields(['type'])
  }
  //2.接收并 控制 radio
  const [type, setType] = useState(1)
  const changeType = (e) => {
    const count = e.target.value
    setType(count)
    // 为了 显示默认的数据 包括点击3张可以添加点击1张显示已有的数据 这里用useRef()
    setFilelist(fileRef.current.slice(0, count))
  }
  // 发布文章
  const add = async (draft, values) => {
    let images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const form = {
      ...values,
      cover: {
        type: type,
        images: images,
      },
    }

    // 10 编辑文章
    if (id) {
      await dispatch(editArticle(draft, { ...form, id }))
    } else {
      await dispatch(addAritcle(draft, form))
    }
    //信息提示
    message.success('操作成功')
    //跳转到文章
    history.push('/home/article')
  }
  //发布文章
  const onFinish = async (values) => {
    add(false, values)
  }
  // 5.校验表单中的 字段属性
  const formRef = useRef()
  // 7. 存入草稿
  const addDraft = async () => {
    // 获取的是form 表单中三个校验的值 是表单的哦
    const values = await formRef.current.validateFields()
    add(true, values)
  }

  // 8.图片预览
  const [isShow, setIsShow] = useState(false)
  const [img, setImg] = useState('')
  const onPreview = (file) => {
    setIsShow(true)
    setImg(file.url || file.response.data.url)
  }
  const handleCancel = () => {
    setIsShow(false)
  }

  // 9.获取编辑传过来的id
  const { id } = useParams()
  useEffect(() => {
    if (!id) return
    dispatch(getArticleInfo(id)).then((res) => {
      // console.log(res)
      formRef.current.setFieldsValue({ ...res, type: res.cover.type })
      setType(res.cover.type)
      const list = res.cover.images.map((item) => {
        // 设置的时候 是url
        return {
          url: item,
        }
      })
      setFilelist(list)
      fileRef.current = list
    })
  }, [id, dispatch])
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          onFinish={onFinish}
          labelCol={{ span: 4 }}
          wrapperCol={{
            span: 20,
          }}
          initialValues={{ content: '', type: type }}
          validateTrigger={['onBlur', 'onChange']}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '标题不能为空' }]}
          >
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '频道不能为空' }]}
          >
            <Channel></Channel>
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator: (_, value) => {
                  if (fileList.length !== value) {
                    return Promise.reject(new Error('上传图片不能为空'))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Radio.Group value={type} onChange={changeType}>
              <Radio value={1}>1张图片</Radio>
              <Radio value={3}>3张图片</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {type > 0 && (
            <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
              <Upload
                listType="picture-card"
                onChange={onChange}
                action={`${process.env.REACT_APP_URL}upload`}
                name="image"
                fileList={fileList}
                maxCount={type}
                onPreview={onPreview}
              >
                {fileList.length < type ? <PlusOutlined></PlusOutlined> : ''}
              </Upload>
            </Form.Item>
          )}

          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '内容不能为空' }]}
          >
            <ReactQuill theme="snow" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '编辑' : '发布'}文章
              </Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        footer={null}
        title="图片预览"
        visible={isShow}
        onCancel={handleCancel}
        width={800}
      >
        <div style={{ textAlign: 'center' }}>
          <img src={img} alt="" style={{ width: 600 }} />
        </div>
      </Modal>
    </div>
  )
}
